package com.ylyq.ylxx.controller;

import com.ylyq.ylxx.constants.AccountConstant;
import com.ylyq.ylxx.context.FilterContextHandler;
import com.ylyq.ylxx.model.ResponseData;
import com.ylyq.ylxx.model.request.GetOauth;
import com.ylyq.ylxx.service.IOauthService;
import com.ylyq.ylxx.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @ClassName AuthController
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/6/23 16:53
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/oAuth")
@Api(description = "巨量引擎的授权")
public class OauthController {
    @Value("${public.config.ouathPath}")
    private String ouathPath;
    @Autowired
    private RedisUtil redisUtils;
    @Autowired
    private IOauthService iOauthService;

    @GetMapping("/isOauth")
    @ApiOperation(value = "获取是否授权")
    public ResponseData isOauth() {
        String access_token = (String) redisUtils.get("access_token" + FilterContextHandler.getUserID());
        if (StringUtils.isBlank(access_token)) {
            String refresh_token = (String) redisUtils.get("refresh_token" + FilterContextHandler.getUserID());
            if (StringUtils.isBlank(refresh_token)) {
                return new ResponseData(ResponseData.Result.FAIL.getCode(), "暂无授权");
            } else
                return new ResponseData(ResponseData.Result.SUCCESS.getCode(), "已经授权");
        } else
            return new ResponseData(ResponseData.Result.SUCCESS.getCode(), "已经授权");
    }

    /**
     * @return void
     * @Author xiaweichao
     * @Description //巨量授权  * @Date 17:14 2020/6/23
     * @Param [response, state]
     **/
    @PostMapping("/getOauth1")
    @ApiOperation(value = "巨量引擎的授权")
    public void getOauth1(HttpServletResponse response, @RequestBody GetOauth getOauth) {
        try {
            //https://ad.oceanengine.com/openapi/audit/oauth.html?app_id=1670727750393863&state="/"&redirect_uri=http://jsteam.qicp.vip/ylyq/oAuth/oAuthCallback
            String OAUTH_URL = AccountConstant.OAUTH_URL.replace("#{state}", getOauth.getState())
                    .replace("#{REDIRECT_URI}", URLEncoder.encode(ouathPath+AccountConstant.OAUTH_REDIRECT_URI, "UTF-8"));
            log.info("回调接口：{}", OAUTH_URL);
            response.sendRedirect(OAUTH_URL);
        }  catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * @return void
     * @Author xiaweichao
     * @Description //巨量授权  * @Date 17:14 2020/6/23
     * @Param [response, state]
     **/
    @PostMapping("/getOauth")
    @ApiOperation(value = "巨量引擎的授权")
    public ResponseData getOauth(HttpServletResponse response, @RequestBody GetOauth getOauth) {
        try {
             String OAUTH_URL = AccountConstant.OAUTH_URL.replace("#{state}", getOauth.getAction()+"{"+FilterContextHandler.getUserID()+"}").replace("#{REDIRECT_URI}", URLEncoder.encode(ouathPath+AccountConstant.OAUTH_REDIRECT_URI, "UTF-8") );
//            String OAUTH_URL = AccountConstant.OAUTH_URL.replace("#{state}", getOauth.getAction()+"{"+getOauth.getUserId()+"}").replace("#{REDIRECT_URI}", URLEncoder.encode(AccountConstant.OAUTH_REDIRECT_URI, "UTF-8") );
            log.info("回调接口：{}", OAUTH_URL);
            // 前端追加“?state=#{state}”跳回对应的前端页面
//            response.sendRedirect(OAUTH_URL);
            return new ResponseData(ResponseData.Result.SUCCESS, OAUTH_URL);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new ResponseData(ResponseData.Result.FAIL);
//        String OAUTH_URL = "https://ad.oceanengine.com/openapi/audit/oauth.html?app_id=1670816140363789&state="+getOauth.getAction()+"{"+getOauth.getUserId()+"}&action="+getOauth.getState()+"&userId="+getOauth.getUserId()+"&scope=%5B130%2C3%2C4%2C5%2C8%2C9%2C12%2C2%2C14%2C112%2C110%5D&material_auth=1&redirect_uri=http%3A%2F%2Fjsteam.qicp.vip%2Fylyq%2FoAuth%2FoAuthCallback&rid=1zkal6s4npf";
    }


    /**
     * @return void
     * @Author xiaweichao
     * @Description //巨量授权后进入的回调  * @Date 17:14 2020/6/23
     * @Param [response, state]
     **/
    @GetMapping("/oAuthCallback")
    @ApiOperation(value = "巨量引擎的授权回调入口,web端不用调用")
    public void oAuthCallback(HttpServletResponse response, HttpServletRequest request, String auth_code, String state,String userId, String action) {
        log.info("===============================巨量引擎进入授权回调地址==========================");
        log.info("auth_code:{},state:{},param:{}", auth_code, state, action);
        userId=state.substring(state.indexOf("{")+1,state.indexOf("}"));
        try {
            // 获取access_token
            String wxAccessToken = iOauthService.getAccessToken(userId, auth_code);
            log.debug("access_token：{}", wxAccessToken);

            // wxAccessToken为空，授权失败，通知前端重新获取授权
            if (StringUtils.isBlank(wxAccessToken)) {
//                wxToken = "invalid";
                // 重定向到授权错误的页面
                String actionResult = ouathPath+AccountConstant.CLIENT_URL + "/page?action=" + action;

//                if (StringUtils.isNotBlank(param)) {
//                    actionResult = actionResult + "&param=" + param;
//                }

                log.info("重定向页面：" + actionResult);
                response.sendRedirect(actionResult);
            } else {
                // 重定向到前端
//            String actionResult = AccountConstant.CLIENT_URL;
                // 重定向到前端
//                String actionResult = AccountConstant.CLIENT_URL + "/page?action=" + state;
                String actionResult = state.substring(0,state.indexOf("{"));
//                String actionResult = "http://192.168.100.121:8081/home";

//                if (StringUtils.isNotBlank(param)) {
//                    actionResult = actionResult + "&param=" + param;
//                }

                log.info("重定向页面：" + actionResult);
                response.sendRedirect(actionResult);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
